<?php
/**
 * 后台用户控制器
 * @author yupoxiong<i@yufuping.com>
 */

namespace app\admin\controller;
use app\admin\model\Ota;
use app\admin\model\OtaCon;
use app\admin\model\OtaImei;
use app\admin\model\OtaUser;
use think\Request;
use app\admin\model\OtaGroup;
use app\admin\validate\OtaGroupValidate;

class OtaGroupController extends Controller
{

    //列表
    public function index(Request $request, OtaGroup $model, OtaImei $otaImei, OtaCon $otaCon)
    {

        $param = $request->param();
        if ($this->user->is_admin == 1) {
            $data = $model->scope('where', $param)
                ->paginate($this->admin['per_page'], false, ['query' => $request->get()]);
        }else{
            $data = $model->scope('where', $param)
                ->where(['ota_account'=>$this->user->account])
                ->paginate($this->admin['per_page'], false, ['query' => $request->get()]);
        }

        $page = $data->render();
        foreach ($data as $k=>$d){
            $data[$k]['ImeiCount'] = $model->OtaImei()->where(['ota_group'=>$d['id']])->count();

            $ota_imei = $otaImei->where(['ota_group'=>$d['id']])->order('id','desc')->limit(1)->find();
            $data[$k]['ota_imei'] = $ota_imei['name'];

            //日 接口请求
            $now = date('Y-m-d',time());
            $start_time = strtotime($now. '00:00:00');
            $end_time = strtotime($now. '23:59:59');
            $allOtaCon = $otaCon->where(['con_account'=>$d['ota_account'],'con_group'=>$d['id']])->whereBetweenTime('create_time',$start_time,$end_time)->order('id','desc')->limit(1)->find();
            $data[$k]['dayOtaCon'] = $allOtaCon['request_num'] ? $allOtaCon['request_num'] : 0;

            //月 接口请求
            $start_month = date('Y-m-01', strtotime($now));
            $end_month = date('Y-m-d', strtotime(date('Y-m-01', strtotime($now)) . ' +1 month -1 day'));
            $start_time = strtotime($start_month. '00:00:00');
            $end_time = strtotime($end_month. '23:59:59');
            $allOtaCon = $otaCon->where(['con_account'=>$d['ota_account'],'con_group'=>$d['id']])->whereBetweenTime('create_time',$start_time,$end_time)->order('id','desc')->limit(1)->find();
            $data[$k]['monthOtaCon'] = $allOtaCon['request_num'] ? $allOtaCon['request_num'] : 0;

            //总 接口请求
            $allOtaCon = $otaCon->where(['con_account'=>$d['ota_account'],'con_group'=>$d['id']])->order('id','desc')->limit(1)->find();
            $data[$k]['totalOtaCon'] = $allOtaCon['request_num'] ? $allOtaCon['request_num'] : 0;

        }

        //关键词，排序等赋值
        $this->assign($request->get());

        $this->assign([
            'data'  => $data,
            'page'  => $page,
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, OtaGroup $model, OtaUser $otaUser, OtaGroupValidate $validate)
    {
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return admin_error($validate->getError());
            }

            $result = $model::create($param);

            $url = URL_BACK;
            if (isset($param['_create']) && $param['_create'] == 1) {
                $url = URL_RELOAD;
            }

            return $result ? admin_success('添加成功', $url) : admin_error();
        }

        if($this->user->is_admin == 1) {
            $UserData = $otaUser->scope('where', ['status' => 1])->select();
        }else{
            $UserData = $otaUser->scope('where', ['status' => 1])->where(['account'=>$this->user->account])->select();
        }

        $this->assign([
            'UserData' => $UserData,
        ]);

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, OtaGroup $model, OtaUser $otaUser, OtaGroupValidate $validate)
    {

        $data = $model::get($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return admin_error($validate->getError());
            }

            $result = $data->save($param);
            return $result ? admin_success() : admin_error();
        }

        if($this->user->is_admin == 1) {
            $UserData = $otaUser->scope('where', ['status' => 1])->select();
        }else{
            $UserData = $otaUser->scope('where', ['status' => 1])->where(['account'=>$this->user->account])->select();
        }

        $this->assign([
            'UserData' => $UserData,
            'data' => $data,
        ]);
        return $this->fetch('add');

    }

    //参数配置
    public function config($id, Request $request, OtaGroup $model, OtaGroupValidate $validate)
    {

        $data = $model::get($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('config')->check($param);
            if (!$validate_result) {
                return admin_error($validate->getError());
            }

            $result = $data->save($param);
            return $result ? admin_success() : admin_error();
        }

        $this->assign([
            'data' => $data,
        ]);
        return $this->fetch('config');

    }


    //删除
    public function del($id, OtaGroup $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return admin_error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return admin_error('ID为' . $id . '的数据无法删除');
            }
        }

        $group = $model->where(['id'=>$id])->find();

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        // 删除可以操作的分组， 如果全部删除，自动将之前的设备的转入默认分组
        $all_group = $model->where(['ota_account'=>$group['ota_account'],'is_operate'=>1])->count();
        if ($all_group <= 0){
            $def_group = $model->where(['ota_account'=>$group['ota_account'],'is_operate'=>0])->find();
            Ota::where(['ota_group'=>$group['id']])->update(['ota_group'=>$def_group['id']]);
        }

        return $result ? admin_success('操作成功', URL_RELOAD) : admin_error();
    }

}
